package zmee.pur.src.formplugin;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.excel.util.ObjectUtils;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.db.tx.TX;
import kd.bos.db.tx.TXHandle;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.scm.pds.common.enums.BidOpenStatusEnums;
import kd.scm.src.common.util.SrcProjectUtil;
import zmee.bid.oa.OABiddocStateApi;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: xw
 * @Date: 2023/02/22/18:17
 * @Description: 定标节点点击废标按钮作废当前流程
 */
public class DecisionRejectedBidBillPlugin extends AbstractBillPlugIn {
    private static Log logger = LogFactory.getLog(DecisionRejectedBidBillPlugin.class);
    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        String operateKey = args.getOperateKey();
        if ("rejectedbid".equals(operateKey)) {
            Long projectId = (Long) this.getModel().getValue("id");
            try (TXHandle h = TX.requiresNew()) {
                try {
                    //重新发起流程
                    //BotpUtil.pushAndSave("src_project", "src_project", projectId);
                    //项目成员
                    DynamicObject projectManObj = BusinessDataServiceHelper.loadSingle("src_project_man",
                            "entryentity,entryentity" + ".entrystatus", new QFilter[]{new QFilter("parentid", "=", projectId)});
                    DynamicObjectCollection entryentity = projectManObj.getDynamicObjectCollection("entryentity");
                    for (DynamicObject object : entryentity) {
                        object.set("entrystatus", "E");
                    }
                    SaveServiceHelper.save(new DynamicObject[]{projectManObj});
                    //标书编制
                    DynamicObject biddocObj = BusinessDataServiceHelper.loadSingle(projectId, "src_biddoc", "bizstatus");
                    isNull(biddocObj);
                    //招标公告
                    DynamicObject publishnoticeObj = BusinessDataServiceHelper.loadSingle(projectId, "src_publishnotice", "bizstatus");
                    isNull(publishnoticeObj);
                    //收费
                    DynamicObject payManageObj = BusinessDataServiceHelper.loadSingle(projectId, "src_paymanage", "bizstatus");
                    isNull(payManageObj);
                    //开标准备
                    DynamicObject bidOpenObj = BusinessDataServiceHelper.loadSingle(projectId, "src_bidopen", "bizstatus");
                    isNull(bidOpenObj);
                    //资质后审
                    DynamicObject aptitudeAuditObj = BusinessDataServiceHelper.loadSingle(projectId, "src_aptitudeaudit2", "bizstatus");
                    isNull(aptitudeAuditObj);
                    //开技术标
                    DynamicObject bidAssessObj = BusinessDataServiceHelper.loadSingle(projectId, "src_bidassess", "bizstatus");
                    isNull(bidAssessObj);
                    //开商务标
                    DynamicObject compareObj = BusinessDataServiceHelper.loadSingle(projectId, "src_compare", "bizstatus");
                    isNull(compareObj);
                    //定标
                    DynamicObject decisionObj = BusinessDataServiceHelper.loadSingle(projectId, "src_decision", "bizstatus");
                    isNull(decisionObj);
                    //项目启动
                    DynamicObject projectObj = BusinessDataServiceHelper.loadSingle(projectId, "src_project", "currentnode," +
                            "terminalnode,openstatus,bizstatus,bidname,org,source,srcbillid");
                    projectObj.set("terminalnode", projectObj.get("currentnode"));
                    projectObj.set("currentnode", 1291999207766400000L);
                    projectObj.set("openstatus", BidOpenStatusEnums.TERMINATED.getValue());
                    projectObj.set("bizstatus", "E");
                    SaveServiceHelper.save(new DynamicObject[]{projectObj});
                    this.getView().invokeOperation("refresh");
                    //下查项目启动单
                    String sourceTypeNumber = ((DynamicObject) this.getModel().getValue("sourcetype")).getString("number");
                    DynamicObject srcType = (DynamicObject) this.getModel().getValue("srctype");
                    String billNo = (String) this.getModel().getValue("billno");
                    long newBillId = SrcProjectUtil.createNewBillId("src_project", sourceTypeNumber, srcType.getLong("id"), true);
                    DynamicObject object = BusinessDataServiceHelper.loadSingle(newBillId, "src_project");
                    if (ObjectUtils.isEmpty(object)) {
                        h.markRollback();
                        this.getView().showMessage("新的项目启动单生成失败！");
                        return;
                    }
                    setProjectPropValue(projectId, projectObj, billNo, newBillId, object);
                    this.getView().showMessage("新的项目启动单项目编号是：" + object.getString("billno"));
                } catch (Throwable e) {
                    h.markRollback();
                    throw e;
                }
            }
        }
    }

    private void isNull(DynamicObject object) {
        if (!Objects.isNull(object)) {
            object.set("bizstatus", "E");
            SaveServiceHelper.save(new DynamicObject[]{object});
        }
    }

    private void setProjectPropValue(Long projectId, DynamicObject projectObj, String billNo, long newBillId, DynamicObject object) {
        object.set("zmee_dczb", true);
        object.set("bidname", projectObj.get("bidname"));
        object.set("org", projectObj.get("org"));
        object.set("source", projectObj.get("source"));
        SaveServiceHelper.save(new DynamicObject[]{object});

        DynamicObject sourceProjectBaseObj = BusinessDataServiceHelper.loadSingle(projectId, "src_project_base");
        DynamicObject targetProjectBaseObj = BusinessDataServiceHelper.loadSingle(newBillId, "src_project_base");
        //投标截止时间
        targetProjectBaseObj.set("stopbiddate", sourceProjectBaseObj.get("stopbiddate"));
        targetProjectBaseObj.set("decisiontype", sourceProjectBaseObj.get("decisiontype"));
        targetProjectBaseObj.set("taxtype", sourceProjectBaseObj.get("taxtype"));
        SaveServiceHelper.save(new DynamicObject[]{targetProjectBaseObj});

        DynamicObject sourceType = (DynamicObject) this.getModel().getValue("sourcetype");
        String number = sourceType.getString("number");
        DynamicObject sourceProjectRuleObj = BusinessDataServiceHelper.loadSingle(projectId, "src_project_rule");
        DynamicObject targetProjectRuleObj = BusinessDataServiceHelper.loadSingle(newBillId, "src_project_rule");
        targetProjectRuleObj.set("zmee_check", true);
        if ("C010405".equals(number)) {
            targetProjectRuleObj.set("winrule", sourceProjectRuleObj.getDynamicObject("winrule"));
            targetProjectRuleObj.set("ruleassess", sourceProjectRuleObj.get("ruleassess"));
            targetProjectRuleObj.set("winerqty", sourceProjectRuleObj.get("winerqty"));
            targetProjectRuleObj.set("biderqty", sourceProjectRuleObj.get("biderqty"));
            targetProjectRuleObj.set("scheme", sourceProjectRuleObj.getDynamicObject("scheme"));
            targetProjectRuleObj.set("otherruleassess", sourceProjectRuleObj.get("otherruleassess"));
            targetProjectRuleObj.set("remark", sourceProjectRuleObj.get("remark"));
            SaveServiceHelper.save(new DynamicObject[]{targetProjectRuleObj});
        } else if ("C010406".equals(number)) {
            targetProjectRuleObj.set("winrule", sourceProjectRuleObj.getDynamicObject("winrule"));
            targetProjectRuleObj.set("winerqty", sourceProjectRuleObj.get("winerqty"));
            targetProjectRuleObj.set("biderqty", sourceProjectRuleObj.get("biderqty"));
            targetProjectRuleObj.set("scheme", sourceProjectRuleObj.getDynamicObject("scheme"));
            targetProjectRuleObj.set("remark", sourceProjectRuleObj.get("remark"));
            targetProjectRuleObj.set("negotiaterule", sourceProjectRuleObj.getString("negotiaterule"));
            targetProjectRuleObj.set("topsupplier", sourceProjectRuleObj.get("topsupplier"));
            targetProjectRuleObj.set("zmee_tpspreads", sourceProjectRuleObj.get("zmee_tpspreads"));
            targetProjectRuleObj.set("extfilter", sourceProjectRuleObj.getDynamicObject("extfilter"));
            targetProjectRuleObj.set("sourcetype", sourceProjectRuleObj.getDynamicObject("sourcetype"));
            SaveServiceHelper.save(new DynamicObject[]{targetProjectRuleObj});
        } else if ("C010415".equals(number)) {
            targetProjectRuleObj.set("winrule", sourceProjectRuleObj.getDynamicObject("winrule"));
            targetProjectRuleObj.set("winerqty", sourceProjectRuleObj.get("winerqty"));
            targetProjectRuleObj.set("biderqty", sourceProjectRuleObj.get("biderqty"));
            targetProjectRuleObj.set("scheme", sourceProjectRuleObj.getDynamicObject("scheme"));
            targetProjectRuleObj.set("remark", sourceProjectRuleObj.get("remark"));
            targetProjectRuleObj.set("negotiaterule", sourceProjectRuleObj.getString("negotiaterule"));
            targetProjectRuleObj.set("topsupplier", sourceProjectRuleObj.get("topsupplier"));
            targetProjectRuleObj.set("zmee_csscoregap", sourceProjectRuleObj.get("zmee_csscoregap"));
            targetProjectRuleObj.set("extfilter", sourceProjectRuleObj.getDynamicObject("extfilter"));
            targetProjectRuleObj.set("sourcetype", sourceProjectRuleObj.getDynamicObject("sourcetype"));
            SaveServiceHelper.save(new DynamicObject[]{targetProjectRuleObj});
        }

        QFilter filter = new QFilter("parentid", "=", projectId);
        DynamicObject sourceObj = BusinessDataServiceHelper.loadSingle("src_purlist_stand", "id", filter.toArray());
        DynamicObject sourcePurListStandObj = BusinessDataServiceHelper.loadSingle(sourceObj.getPkValue(), "src_purlist_stand");
        DynamicObjectCollection entryEntity = sourcePurListStandObj.getDynamicObjectCollection("entryentity");

        QFilter filter1 = new QFilter("parentid", "=", newBillId);
        DynamicObject targetObj = BusinessDataServiceHelper.loadSingle("src_purlist_stand", "id", filter1.toArray());
        DynamicObject targetPurListStandObj = null;
        if (null == targetObj) {
            targetPurListStandObj = BusinessDataServiceHelper.newDynamicObject("src_purlist_stand");
        } else {
            targetPurListStandObj = BusinessDataServiceHelper.loadSingle(targetObj.getPkValue(), "src_purlist_stand");
        }

        targetPurListStandObj.set("parentid", newBillId);
        targetPurListStandObj.set("entitykey", "src_purlist_stand");
        targetPurListStandObj.set("curr", 1L);
        targetPurListStandObj.set("taxtype", sourcePurListStandObj.get("taxtype"));
        targetPurListStandObj.set("sumqty", sourcePurListStandObj.get("sumqty"));
        targetPurListStandObj.set("sumtax", sourcePurListStandObj.get("sumtax"));
        targetPurListStandObj.set("sumamount", sourcePurListStandObj.get("sumamount"));
        targetPurListStandObj.set("sumtaxamount", sourcePurListStandObj.get("sumtaxamount"));
        targetPurListStandObj.set("origin", sourcePurListStandObj.get("origin"));
        targetPurListStandObj.set("pentitykey", sourcePurListStandObj.get("pentitykey"));
        targetPurListStandObj.getDynamicObjectCollection("entryentity").clear();

        Map<String, List<DynamicObject>> listMap =
                entryEntity.stream().collect(Collectors.groupingBy(s -> s.get("material.number") + "_" + s.get("entryrcvorg.id")));
        for (Map.Entry<String, List<DynamicObject>> listEntry : listMap.entrySet()) {
            List<DynamicObject> entry = listEntry.getValue();
            DynamicObject dynamicObject = entry.get(0);
            DynamicObjectCollection collection = targetPurListStandObj.getDynamicObjectCollection("entryentity");
            DynamicObject entity = collection.addNew();
            setValues(newBillId, billNo, dynamicObject, entity);
        }
        OperationResult operation = OperationServiceHelper.executeOperate("save", "src_purlist_stand", new DynamicObject[]{targetPurListStandObj}, OperateOption.create());
        logger.info("=======operation=======:"+operation);
        //SaveServiceHelper.save(new DynamicObject[]{targetPurListStandObj});
    }

    private void setValues(Long projectId, String billNo, DynamicObject entry, DynamicObject entity) {
        entity.set("seq", entry.get("seq"));
        entity.set("packagename", entry.get("packagename"));
        entity.set("category", entry.get("category"));
        entity.set("material", entry.get("material"));
        entity.set("materialnane", entry.get("materialnane"));
        entity.set("materialmodel", entry.get("materialmodel"));
        entity.set("unit", entry.get("unit"));
        entity.set("qty", entry.get("qty"));
        entity.set("tax", entry.get("tax"));
        entity.set("turns", entry.get("turns"));
        entity.set("entrystatus", entry.get("entrystatus"));
        entity.set("currency", entry.get("currency"));
        entity.set("package", entry.get("package"));
        entity.set("project", projectId);
        entity.set("purlist", entry.get("purlist"));
        entity.set("bizamount", entry.get("bizamount"));
        entity.set("rank", entry.get("rank"));
        entity.set("sysresult", entry.get("sysresult"));
        entity.set("result", entry.get("result"));
        entity.set("orderratio", entry.get("orderratio"));
        entity.set("bidmaterial", entry.get("bidmaterial"));
        entity.set("entryparentid", projectId);
        entity.set("pkgamount", entry.get("pkgamount"));
        //entity.set("suppliertype", entry.get("suppliertype"));
        //entity.set("supplier", entry.get("supplier"));
        //entity.set("suppliername", entry.get("suppliername"));
        entity.set("exratetable", entry.get("exratetable"));
        entity.set("exratedate", entry.get("exratedate"));
        entity.set("exrate", entry.get("exrate"));
        entity.set("quotation", entry.get("quotation"));
        entity.set("entryrcvorg", entry.get("entryrcvorg"));
        entity.set("taxitem", entry.get("taxitem"));
        entity.set("taxrate", entry.get("taxrate"));
        entity.set("zmee_easnumber", entry.get("zmee_easnumber"));
        entity.set("zmee_easentry", entry.get("zmee_easentry"));

        entity.set("effectdate", entry.get("effectdate"));
        entity.set("duedate", entry.get("duedate"));
        entity.set("org", entry.get("org"));
        entity.set("baseunit", entry.get("baseunit"));
        entity.set("reqsource", entry.get("reqsource"));
        entity.set("srcbillno", billNo);
    }
}
